package com.luoxue.mito.config.aspect;

import com.luoxue.mito.common.ResultBody;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.PagedModel;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

@Aspect
//@Component
public class ResponseAspect {

    // 配置织入点
    @Pointcut("@within(org.springframework.data.rest.webmvc.RepositoryRestController) " +
            "|| @within(org.springframework.stereotype.Controller)" +
            "|| @within(org.springframework.web.bind.annotation.RestController)")
//    @Pointcut("execution(* *..*.*Controller.*(..))")
    public void responsePointCut() {
    }

    @Around("responsePointCut()")
    public Object responseAround(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed = pjp.proceed();
        if (proceed instanceof ResultBody) {
            return proceed;
        } else if (proceed instanceof CollectionModel) {
            CollectionModel<?> entity = (CollectionModel<?>) proceed;
            return CollectionModel.of(ResultBody.ok(entity.getContent()));
        }else if (proceed instanceof ResponseEntity) {
            ResponseEntity<?> entity = (ResponseEntity<?>) proceed;
            return ResponseEntity.ok(ResultBody.ok(entity.getBody()));
        } else {
            return ResultBody.ok(proceed);
        }
    }
}
